﻿using System;
using System.Collections;
using System.Text;
using Telerik.Framework.Search;

namespace SelArom.Net.Sitefinity.IndexProviders.GenericContent
{
	/// <summary>
	/// Generic Content Items indexed by the GenericContentIndexProvider
	/// </summary>
	public class GenericContentIndexerInfo : IIndexerInfo
	{
		private string _url;
		private Hashtable _metaFields;
		private string _content;
		private Guid _id;


		public GenericContentIndexerInfo(string url, Hashtable metaFields, string content, Guid ID)
		{
			_url = url;
			_metaFields = metaFields;
			_content = content;
			_id = ID;
		}

		protected string GetMetaData()
		{
			var sb = new StringBuilder();
			var meta = _metaFields.GetEnumerator();

			while (meta.MoveNext())
			{
				sb.AppendLine();
				sb.Append("<");
				sb.Append(meta.Key);
				sb.Append(">");
				sb.Append(meta.Value == null ? string.Empty : meta.Value.ToString());
				sb.Append("</");
				sb.Append(meta.Key);
				sb.Append(">");
			}
			return sb.ToString();
		}

		#region IIndexerInfo Members

		public Encoding Encoding
		{
			get { return Encoding.UTF8; }
		}

		public byte[] GetData()
		{
			var text = _content;

			//If we have any meta data add it to the index content
			if (_metaFields.Count > 0)
				text += GetMetaData();

			return Encoding.GetBytes(text);
		}

		public string ResolveIndexPath()
		{
			return Path;
		}

		public string MimeType
		{
			get { return "text/html"; }
		}

		public string Path
		{
			get { return _url; }
		}

		#endregion

		#region IIndexerInfo Members

		public string Culture
		{
			get { return string.Empty; }
		}

		public Guid ItemID
		{
			get { return _id; }
		}

		#endregion
	}
}